package com.ly.mp.busicen.rule.field.article;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.config.XruleConfig;
import com.ly.mp.busicen.rule.field.article.ext.FieldArticle;
import com.ly.mp.busicen.rule.flow.FlowException;

/**
 * @Description: com.ly.mp.busicen.rule.field.FiledRuleLoader.articleLoad() 中已经加载了 t_prc_db_sence_validatecolum
 * @author wangzhen
 * @date 2024-01-24 04:17:00
 */
public class FieldArticleContainer implements IFieldArticleContainer{
	
	Logger log = LoggerFactory.getLogger(FieldArticleContainer.class);
	
	@Autowired
	XruleConfig xruleConfig;

	private List<FieldArticle> articles = new ArrayList<FieldArticle>();
	private List<FieldArticle> articlesCust = new ArrayList<FieldArticle>();
	
	private Map<String,List<IFieldArticle>> articlesCache = new ConcurrentHashMap<>();	
	
	public List<FieldArticle> getArticles() {
		return articles;
	}

	public void setArticles(List<FieldArticle> articles) {
		this.articles = articles;
	}
	
	public void setArticlesCust(List<FieldArticle> articlesCust) {
		this.articlesCust = articlesCust;
	}

	// rule 就是 CONCAT(BUSINESSFLOW_SENCECODE,DATA_TYPE)
	// ctx 可以这个 FlowUserMode.currentContext(null)
	@Override
	public List<IFieldArticle> getArticles(String rule,Map<String, Object> ctx) {
		if (StringUtils.isEmpty(ctx.get("oemCode"))||StringUtils.isEmpty(ctx.get("brandCode"))) {
			throw new FlowException("获取规则时对应对应厂商或品牌编码为空，无法找到配置");
		}
		String oemCode = String.valueOf(ctx.get("oemCode"));
		String brandCode = String.valueOf(ctx.get("brandCode"));
		List<IFieldArticle> list=null;
		
		if(xruleConfig.xruleExtendCfg().currentCustMode()) {
				list = articlesCust.stream().filter(m->			
			rule.equals(m.articleName())
			&&brandCode.equals(m.getColumnBrand())
			&&oemCode.equals(m.getColumnOem())
					).map(m->m).collect(Collectors.toList());
		}
		if(list==null||list.isEmpty()) {
			list = articles.stream().filter(m->
				rule.equals(m.articleName()) // BUSINESSFLOW_SENCECODE + DATA_TYPE
				&&brandCode.equals(m.getColumnBrand()) // CAR_BRAND_CODE 都是1
				&&oemCode.equals(m.getColumnOem()) // OEM_CODE 都是1
			).map(m->m).collect(Collectors.toList());
		}else {
			log.info("流程【{}】规则引擎字段校验使用客制化配置",rule);
		}
		return list;
	}

	@Override
	public void cleanCache() {
		articlesCache.clear();
	}


}
